/*
本例演示如何通过开放的接口 https://api.omniwallet.org/v2/address/addr/  进行USDT相关的操作

1、 演示如何获取当前地址的余额

2、 演示如何发送一笔USDT的转账

cnpm i bitcoinjs-lib


 */



//import * as bitcoin from "bitcoinjs-lib";

var httpclient = require('./httpclient');
var querystring = require('querystring');
//var bitcoin = require('bitcoinjs-lib');
let bitcoin = require('bitcoinjs-lib');

/****
 * 获取指定地址USDT的余额
 */
async function  getAddressBlance( address ) {



    var data = {
        addr:address};


    var content = querystring.stringify(data);

    var options={

         protocol: 'https:',
         hostname:'api.omniexplorer.info',
         port:443,
         path:'/v1/address/addr/',
         method:'POST',
         rejectUnauthorized: false,
         requestCert: true,
         headers:{
             'Content-Type':'application/x-www-form-urlencoded',
             'Content-Type':'application/x-www-form-urlencoded'
         }
     }



    let contents = await httpclient.httppost(options,content);
    let contentsarr = JSON.parse(contents);

    let propertyname = 'bitcion';
    let payment = 0;

    let balance = contentsarr['balance'];

    if( balance.indexOf('Error') >=0 ){
            payment =0 ;
            propertyname = 'bitcion';
    }else{
        for( let ind = 0 ; ind<contentsarr['balance'].length;ind++ ){

            let item = contentsarr['balance'][ind];
            let propertyinfo = item['propertyinfo'];
            propertyname = propertyinfo['propertyname'];
            payment = item['value'];

            if( propertyname === 'TetherUS' ) break;


        }
    }


    return {'propertyname': propertyname, 'payment': payment};

}


async function testblance(){

    let checkresult = await getAddressBlance('1L5Fmma1mHXcZH1cYJbWrrF93GQRJRhM78');
    console.info(`${JSON.stringify(checkresult)}`);

}

/////////=========================================================================================================================================================/////////
/////////=========================================================================================================================================================/////////
/////////=========================================================================================================================================================/////////
/////////=========================================================================================================================================================/////////
/////////=========================================================================================================================================================/////////
/////////=========================================================================================================================================================/////////

/***
 *
 *
 *
 */


function addPreZero(num){
    var t = (num+'').length,
        s = '';
    for(var i=0; i<16-t; i++){
        s += '0';
    }
    return s+num;
}


function usdtSign(privateKey, utxo, feeValue, usdtValue, fromAddress, toAddress) {
    var txb = new bitcoin.TransactionBuilder();
    var set = bitcoin.ECPair.fromWIF(privateKey);
    const fundValue = 546;
    var usdtAmount = parseInt(usdtValue*1e8).toString(16);
    var totalUnspent = 0;
    for(var i = 0; i < utxo.length; i++){
        totalUnspent = totalUnspent + utxo[i].value;
    }
    const changeValue = totalUnspent - fundValue - (feeValue*1e8);
    if (totalUnspent < feeValue + fundValue) {
        console.log("Total less than fee");
        return constant.LessValue;
    }
    for(var i = 0; i< utxo.length; i++){
        txb.addInput(utxo[i].tx_hash_big_endian, utxo[i].tx_output_n, 0xfffffffe);
    }
    const usdtInfo = [
        "6f6d6e69",
        "0000",
        "00000000001f",
        addPreZero(usdtAmount)
    ].join('');
    const data = Buffer.from(usdtInfo, "hex");
    const omniOutput = bitcoin.script.compile([
        bitcoin.opcodes.OP_RETURN,
        data
    ]);
    txb.addOutput(toAddress, fundValue);
    txb.addOutput(omniOutput, 0);
    txb.addOutput(fromAddress, changeValue);
    for(var i = 0;i < utxo.length; i++){
        txb.sign(0, set);
    }
    return txb.buildIncomplete().toHex();
};



function getUsdtSigin(){

    var utxo ={
        "unspent_outputs":[
            {
                "tx_hash":"38ab83bffc1c2e0b9a47eb3f57f3016419556071dd14f2a25661bde9f9e8f526",
                "tx_hash_big_endian":"06c55450083ce1c1119422b27faedf598672945e9436de8c517275ac57e4f11b",
                "tx_index":399167492,
                "tx_output_n": 2,
                "script":"76a91479b275dd5f136c241f3c28549b4c338177d5cb2188ac",
                "value": 9.999,
                "value_hex": "9.ffbe76c8b4398",
                "confirmations":0
            }
        ]
    }

    //03d408573ceb49006f15b78069e56ac59dffd3f546d900d323a65f125798442b2b

    var privateKey = "5HqyNMphd6XDDa5WVoALfx8oQsycTemxfHkR7EMeTTw7Fg5unpF";
    var usdtValue = 9.997;
    var feeValue = 0.002;
    var fromAddress = "1P3mktqkNwGai5zPv9E3Y1pz1EJBWwZPAV";
    var toAddress = "18kH4DYyEjoyBLXWaaxbHTeDsn7CBAskfD";
    var sign = usdtSign(privateKey, utxo.unspent_outputs, feeValue, usdtValue, fromAddress, toAddress);
    console.log(sign);

    return sign;


}



async function sendtransaction(signtx){


    var data = {
        signedTransaction:signtx};


    var content = querystring.stringify(data);

    var options={

        protocol: 'https:',
        hostname:'api.omniexplorer.info',
        port:443,
        path:'/v1/transaction/pushtx/',
        method:'POST',
        rejectUnauthorized: false,
        requestCert: true,
        headers:{
            'Content-Type':'application/x-www-form-urlencoded',
            'Content-Type':'application/x-www-form-urlencoded'
        }
    }



    let contents = await httpclient.httppost(options,content);

    return contents;

}


async function sendtx() {

    let result = await sendtransaction('02000000011bf1e457ac7572518cde36945e94728659dfae7fb2229411c1e13c085054c506020000008b483045022100cd5762c8cf585239bb5a3d6996d5f7a94426facf169b10ae55f6be46a9fe0f430220486130edd7c34875ef56d6b301ee22d4bdeb9a87f44d6727c88a71ecbdb4ec6201410403c4110a821ee86a57fc36c3f87d4f57557ea10dcdf76fa5b1c59f629fdd1791b5fd12dfdff71d9ee489b7c8ff56060dc7e2ee2471ab4e018a7afb60e41c7faffeffffff0322020000000000001976a91454f82b54c82904451023ad3659f448f2ba5d963d88ac0000000000000000166a146f6d6e69000000000000001f000000003b963620a4be1100000000001976a914f1d8f5d327acb4335b934c721b691b70474a37ea88ac00000000');

    console.info(result);

}


//sendtx();


//getUsdtSigin();

testblance();
/*
const crypto = require(`crypto`);
const ecdh = crypto.createECDH('secp256k1');
const bs58 = require(`bs58`);
// 0 - Having a private ECDSA key
var privateKey = crypto.randomBytes(32);
console.log(`Private key:[${privateKey.toString(`hex`)}]`);

console.log(crypto.createHash('sha256').update(strSeed).digest('hex'));
*/


/*
const wif = require('wif');
let encoded = wif.encode(
    0x80, // 0x80前缀
    Buffer.from('03d408573ceb49006f15b78069e56ac59dffd3f546d900d323a65f125798442b2b', 'hex'), // 转换为字节
    false // 非压缩格式
);
console.log(encoded);*/
